package graphics.client;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Isaac
 * This class creates a client which sends messages and recieve the server response
 * the client connect to the server through port 9876
 */

public class Client {

	public Client(){
	}

	/**
	 *
	 * @return message to be sent
	 *
	 * This procedure gets a message from the standard input
	 */
	public String getCommandMessage(){

		BufferedReader inFromUser =
			new BufferedReader(new InputStreamReader(System.in));
		String sentence="";
		try {
			sentence = inFromUser.readLine();
		} catch (IOException e) {

		}
		return sentence;
	}
	/**
	 * This procedure send a message to server
	 *
	 * @param msg
	 * @throws IOException
	 */
	public void sendMessage(String msg) throws IOException{
		System.out.println(msg);
		DatagramSocket clientSocket = new DatagramSocket();

		InetAddress IPAddress = InetAddress.getByName("127.0.0.1");

		byte[] sendData = new byte[1024];
		byte[] receiveData = new byte[1024];
		sendData = msg.getBytes();
		DatagramPacket sendPacket =
			new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

		clientSocket.send(sendPacket);

		DatagramPacket receivePacket =
			new DatagramPacket(receiveData, receiveData.length);

		clientSocket.receive(receivePacket);

	//	String modifiedSentence =
	//		new String(receivePacket.getData());

	//	System.out.println("FROM SERVER:" + modifiedSentence);
		clientSocket.close();
	}

	/**
	 * This main is to use if the client is used as a stand alone application
	 * @param args
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception
	{

		Client c = new Client();

		String sentence = "";
		sentence = c.getCommandMessage();
		while (sentence.compareTo("exit") != 0){
			c.sendMessage(sentence);
			sentence = c.getCommandMessage();
		}
	}
}
